package com.eastrobot.doc.poitlconvert.util;

import org.apache.commons.lang3.StringUtils;
import org.mvel2.MVEL;
import org.mvel2.ParserContext;
import java.io.Serializable;
import java.lang.reflect.Method;

/**
 * MVEL 编译
 */
public class MVELCompiler {

    private static final MVELCompiler instance = new MVELCompiler();
    private static ParserContext context;

    private MVELCompiler() {
        context = new ParserContext();
        // 将 UserFunction 类中的所有方法加载到 context 中
        Method[] declaredMethods = MvelFunctionUtil.class.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            context.addImport(declaredMethod.getName(), declaredMethod);
        }
    }

    public static MVELCompiler getInstance() {
        return instance;
    }

    public Serializable compile(String expression) {
        if (StringUtils.isNotEmpty(expression)) {
            return MVEL.compileExpression(expression, context);
        }
        return null;
    }
}